package com.example.algorithm.DealLock;

/**
 * 死锁: 两个线程需要的资源被双方持有,都不释放,导致死锁
 * Created by ZMJ on 2020/1/10.
 */
public class DeadLockTest {

    private static String A = "A";
    private static String B = "B";

    public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (A) {
                    System.out.println("t1获得了A的资源,睡一会儿.");
                    try {
                        Thread.sleep(1000l);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    synchronized (B) {
                        System.out.println("t1获得了B的资源");
                    }
                }
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (B) {
                    System.out.println("t2获得了B的资源,睡一会儿.");
                    try {
                        Thread.sleep(1000l);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (A) {
                        System.out.println("t2获得了A的资源");
                    }
                }
            }
        });

        // 开启线程
        t1.start();
        t2.start();
        // 结果:互相等待,死锁
        //t1获得了A的资源,睡一会儿.
        //t2获得了B的资源,睡一会儿.
    }

}
